package com.azdebugit.future.vip.executorcompletion.test;

import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
 
/**
 * 描    述：多线程业务测试
 * 作    者：java潇邦
 * 时    间：2016-09-01
 */
@Component
public class BusinessMuitThreadService {
 
    private static final Logger logger = LoggerFactory.getLogger(BusinessMuitThreadService.class);
 
    @Autowired
    private BatchContainerExecutor batchContainerExecutor;
    @Autowired
    private ThirdService thirdService;
 
    /**
     * 需求：
     * 1.传入的barcodeList大于1W条
     * 2.第三方接口,单次最多支持查询10条记录
     * 3.多线程并发调用第三方接口
     * 4.由BatchContainerExecutor容器去收集线程
     * 5.照着这个抄变成自己的业务逻辑
     */
    public Map<String, String> getProductMap(final String vendorCode, List<String> barcodeList) {
        List<List<String>> pList = Lists.partition(barcodeList, 10);
        List<Callable<Object>> tasks = new ArrayList<Callable<Object>>(barcodeList.size());
        for (List partition : pList) {
            tasks.add(new MapCallable(vendorCode, barcodeList, thirdService));//添加一个任务
        }
        Map<String, String> map = new HashMap<String, String>(barcodeList.size());
        List<Object> retList = batchContainerExecutor.execute(tasks);
        for (Object obj : retList) {
            if (obj instanceof Map) {
                map.putAll((Map) obj);
            } else {
                logger.warn("非法的数据:{}", obj);
            }
        }
        return map;
    }
 
    /**
     * 描    述：多线程查询商品信息,并将每个线程的结果收集起来,返回一个大List
     * 作    者：java潇邦
     * 时    间：2016-09-01
     */
    public List getProductList(final String vendorCode, List<String> barcodeList) {
        List<List<String>> pList = Lists.partition(barcodeList, 10);
        List<Callable<Object>> tasks = new ArrayList<Callable<Object>>(barcodeList.size());
        for (List partition : pList) {
            tasks.add(new ListCallable(vendorCode, barcodeList, thirdService));//添加一个任务
        }
 
        List list = new ArrayList(barcodeList.size());
        List<Object> retList = batchContainerExecutor.execute(tasks);
        for (Object obj : retList) {
            if (obj instanceof List) {
                list.addAll((List) obj);
            } else {
                logger.warn("非法的数据:{}", obj);
            }
        }
        return list;
    }
 
}